package com.jo.topic;

import com.google.common.collect.Lists;
import com.jo.Config;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * @author Jo
 * @date 2017/12/7
 */
public class Consumer2 {
    public static void main(String[] args) {
        List<String> routingKeys = Lists.newArrayList("*.paint.*");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Config.host);
        connectionFactory.setPort(Config.port);
        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            //获得一个临时队列，名字是随机的。在消费者退出后，队列将会删除
            String queueName = channel.queueDeclare().getQueue();
            channel.exchangeDeclare(Producer.EXCHANGENAME, "topic");
            for (String routingKey : routingKeys) {
                channel.queueBind(queueName, Producer.EXCHANGENAME, routingKey);
            }
            System.out.println("消费者2已成功开启");
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body, "utf-8");
                    System.out.println("消费者2获得消息:" + msg);
                }
            };
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
